﻿using System;

using MonoMac.OpenGL;

using System.Drawing;
using System.Drawing.Imaging;

namespace Storyteller.Framework.Graphics
{
	public class Texture : IDisposable
	{
		internal int TextureId { get { return textureId; } }

		public int Width { get { return width; } }
		public int Height { get { return height; } }

		protected Texture()
		{
		}

		public Texture(string fileName)
		{
			if (String.IsNullOrEmpty(fileName))
				throw new ArgumentException(fileName);

			textureId = GL.GenTexture();
			GL.BindTexture(TextureTarget.Texture2D, textureId);

			Bitmap bmp = new Bitmap(fileName);
			BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

			width = bmp.Width;
			height = bmp.Height;

			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);

			GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
				MonoMac.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);

			bmp.UnlockBits(bmp_data);

			GL.Enable(EnableCap.Texture2D);
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					// dispose of managed resources
				}

				// dispose of unmanaged resources
				if (handleDisposing)
				{
					GL.DeleteTexture(textureId);
				}

				disposed = true;
			}
		}

		bool disposed = false;

		protected int width, height;

		protected int textureId;
		protected bool handleDisposing = true;
	}
}
